// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const { httpToCloud } = require('custom-utils');
module.exports = {
  _before: function () {
    // 通用预处理器
  },
  async add(params = {}) {
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    return dbJQL.collection('dc-bizhi-piclist').add(params);
  },
  async list({
    pageSize = 5,
    currentPage = 1,
    viewSort = '',
    downloadSort = '',
    classid = '',
  } = {}) {
    pageSize = Math.min(100, pageSize);
    let skip = (currentPage - 1) * pageSize;
    let order = 'createTime desc';
    let where = {};
    if (viewSort) {
      order = `view_count ${viewSort},createTime desc`;
    }
    if (downloadSort) {
      order = `download_count ${downloadSort},createTime desc`;
    }
    console.log('🌺 ~ order:🌳', order);
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    if (classid) {
      where.classid = classid;
    }
    let picTemp = dbJQL
      .collection('dc-bizhi-piclist')
      .where(where)
      .orderBy(order)
      .skip(skip)
      .limit(pageSize)
      .getTemp();
    let userTemp = dbJQL
      .collection('uni-id-users')
      .field('_id,nickname')
      .getTemp();
    let classTemp = dbJQL
      .collection('dc-bizhi-classify')
      .field('_id,name')
      .getTemp();
    return await dbJQL
      .collection(picTemp, userTemp, classTemp)
      .field(
        `picurl,description,score,tabs,checked,view_count,createTime,picurl,download_count,score_count,
	user_id.nickname as nickname,
	classid.name as classname
	`
      )
      .get({ getCount: true });
  },
  async remove(ids = []) {
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    let { data } = await dbJQL
      .collection('dc-bizhi-piclist')
      .where(`_id in ${JSON.stringify(ids)}`)
      .field('picurl')
      .get();
    let urls = data.map((item) => httpToCloud(item.picurl));
    let promise1 = uniCloud.deleteFile({
      fileList: urls,
    });

    let promise2 = dbJQL
      .collection('dc-bizhi-piclist')
      .where(`_id in ${JSON.stringify(ids)}`)
      .remove();

    const [, result] = await Promise.all([promise1, promise2]);
    return result;
  },
  async item(id) {
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    return await dbJQL
      .collection('dc-bizhi-piclist')
      .doc(id)
      .field(
        `picurl,description,score,tabs,checked,classid
	`
      )
      .get({ getOne: true });
  },
  async update(params = {}) {
    let { _id, ...data } = params;
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    return await dbJQL.collection('dc-bizhi-piclist').doc(_id).update(data);
  },
  async search({
    pageSize = 5,
    currentPage = 1,
    classid = '',
    keyword = '',
  } = {}) {
    pageSize = Math.min(100, pageSize);
    let skip = (currentPage - 1) * pageSize;
    let where = {};
    if (classid) {
      where.classid = classid;
    }
    if (keyword) {
      where = {
        ...where,
        // $or:[
        // 	{description:{$regex:keyword,$options:'i'}},
        // 	{tabs:{$elemMatch:{$regex:keyword,$options:'i'}}}
        // ]
        $or: [
          { description: { $regex: keyword, $options: 'i' } },
          { tabs: { $regex: keyword, $options: 'i' } },
        ],
      };
    }
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    return await dbJQL
      .collection('dc-bizhi-piclist')
      .where(where)
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .field("_id,picurl")
      .get({
        getCount: true,
      });
  },
  /**
   * method1方法描述
   * @param {string} param1 参数1描述
   * @returns {object} 返回值描述
   */
  /* 
	method1(param1) {
		// 参数校验，如无参数则不需要
		if (!param1) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		// 业务逻辑
		
		// 返回结果
		return {
			param1 //请根据实际需要返回值
		}
	}
	*/
};
